<template>
  <scroll-view class="flex-col page mine" scroll-y @scroll="onPageScroll">
    <view class="flex-col section" :style="{ paddingTop: navHeight + 'px' }">
      <xlm-top-nav :scrollTop="scrollTop" title="比赛直播" />

      <!-- 页面内容 -->
      <view class="live-list-page">
        <!-- 顶部Banner -->
        <view class="banner-section">
          <image class="banner" :src="imgUrl + 'banner-bg.jpg'" mode="aspectFill" />
          <view class="banner-overlay">
            <text class="banner-title">精彩赛事直播</text>
            <text class="banner-subtitle">实时观看，精彩不错过</text>
          </view>
        </view>

        <!-- 直播状态提示 -->
        <view v-if="isUpdatingChannels" class="updating-status">
          <view class="loading-spinner"></view>
          <text class="updating-text">正在更新直播状态...</text>
        </view>

        <!-- 直播列表 -->
        <view class="live-list">
          <view v-for="(item, idx) in filteredList" :key="`${item.id || idx}_${item.updateTime || Date.now()}`"
            class="live-card" :class="{
              'channels-live': item.isChannelsLive,
              'live-now': item.isLive,
              replay: !item.isLive
            }" @tap="
              item.isChannelsLive
                ? onChannelsLive(item)
                : item.isLive
                  ? onNormalLive(item)
                  : onReplay(item)
            ">
            <!-- 直播封面 -->
            <view class="live-cover">
              <image class="live-img" :src="item.img" mode="aspectFill" />

              <!-- 视频号标识 -->
              <view v-if="item.isChannelsLive" class="channels-badge">
                <text class="badge-text">视频号</text>
              </view>

              <!-- 分类标签 -->
              <view class="category-badge">
                <text class="category-text">{{ item.category || '体育' }}</text>
              </view>
            </view>

            <!-- 直播信息 -->
            <view class="live-info">
              <view class="title">{{ item.title }}</view>
              <view class="time">{{ item.time }}</view>

              <!-- 视频号直播特有信息 -->
              <view v-if="item.isChannelsLive" class="channels-info">
                <text class="nickname">{{ item.channelsInfo?.nickname }}</text>
                <text class="signature">{{ item.channelsInfo?.signature }}</text>
                <text v-if="item.updateTime" class="update-time">
                  更新时间: {{ formatTime(item.updateTime) }}
                </text>
              </view>

              <!-- 普通直播信息 -->
              <view v-else class="normal-live-info">
                <view class="match-info">
                  <text class="team-home">{{ item.homeTeam || '主队' }}</text>
                  <text class="vs">VS</text>
                  <text class="team-away">{{ item.awayTeam || '客队' }}</text>
                </view>
                <view class="match-details">
                  <text class="venue">{{ item.venue || '比赛场地' }}</text>
                  <text class="viewers" v-if="item.viewerCount">
                    观看: {{ formatViewerCount(item.viewerCount) }}
                  </text>
                </view>
              </view>
            </view>

            <!-- 操作按钮 -->
            <view class="action-buttons">
              <view v-if="!item.isLive" class="replay-btn">
                <image :src="imgUrl + 'replay-icon.png'" class="btn-icon" mode="aspectFit" />
                <text class="btn-text">查看回放</text>
              </view>
              <view v-else class="live-btn">
                <image :src="imgUrl + 'live-icon.png'" class="btn-icon" mode="aspectFit" />
                <text class="btn-text">
                  {{ item.isChannelsLive ? '进入直播' : '观看直播' }}
                </text>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="filteredList.length === 0 && !isLoading && searchKeyword" class="empty-state">
          <image :src="imgUrl + 'empty-live.png'" class="empty-icon" mode="aspectFit" />
          <text class="empty-text">没有找到相关直播</text>
          <text class="empty-hint">请尝试其他关键词或刷新页面</text>
        </view>

        <!-- 加载状态 -->
        <view v-if="isLoading" class="loading-state">
          <view class="loading-spinner"></view>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 加载更多
        <view v-if="hasMore && !isLoading && list.length > 0" class="load-more">
          <button class="load-more-btn" @tap="loadMore" :disabled="isLoadingMore">
            {{ isLoadingMore ? '加载中...' : '加载更多' }}
          </button>
        </view> -->
      </view>
    </view>
  </scroll-view>
</template>

<script setup>
  import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
  import { useOutsideAppStore } from '@/store/app'
  import { imgUrl } from '@/utils/config'
  import { onShow, onHide } from '@dcloudio/uni-app'
  import { useRequest } from '@/api'

  const { API_EVENT_LIVE_POST, API_HOME_EVENT_POST } = useRequest()
  const appStore = useOutsideAppStore()
  const navHeight = computed(() => appStore.navHeight)
  const scrollTop = ref(0)
  const isLoading = ref(false)
  const isLoadingMore = ref(false)
  const hasMore = ref(true)
  const feedId = ref('')
  // 搜索和筛选
  const searchKeyword = ref('')
  const activeFilter = ref('all')
  const filterTabs = ref([
    { key: 'all', label: '全部', count: 0 },
    { key: 'live', label: '直播中', count: 0 },
    { key: 'channels', label: '视频号', count: 0 },
    { key: 'replay', label: '回放', count: 0 }
  ])

  // 视频号配置
  const channelsConfig = ref([])

  // 数据状态
  const channelsInfo = ref(null)
  const list = ref([])
  let statusCheckTimer = null

  const onPageScroll = (e) => {
    scrollTop.value = e.detail.scrollTop
  }

  // 过滤后的列表
  const filteredList = computed(() => {
    let filtered = list.value

    // 搜索过滤
    if (searchKeyword.value) {
      filtered = filtered.filter(
        (item) =>
          item.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
          (item.channelsInfo?.nickname &&
            item.channelsInfo.nickname.toLowerCase().includes(searchKeyword.value.toLowerCase())) ||
          (item.homeTeam &&
            item.homeTeam.toLowerCase().includes(searchKeyword.value.toLowerCase())) ||
          (item.awayTeam && item.awayTeam.toLowerCase().includes(searchKeyword.value.toLowerCase()))
      )
    }

    // 类型过滤
    switch (activeFilter.value) {
      case 'live':
        filtered = filtered.filter((item) => item.isLive)
        break
      case 'channels':
        filtered = filtered.filter((item) => item.isChannelsLive)
        break
      case 'replay':
        filtered = filtered.filter((item) => !item.isLive)
        break
      default:
        break
    }

    return filtered
  })

  // 查看回放
  function onReplay(item) {
    // 如果是视频号回放，使用微信原生播放器
    if (item.isChannelsLive && item.channelsInfo) {
      onChannelsReplay(item)
    } else {
      // 普通回放，跳转到回放页面
      // uni.navigateTo({
      //   url: `/pages/liveReplay/index?id=${item.id}&title=${encodeURIComponent(item.title)}&time=${encodeURIComponent(item.time)}`
      // })
    }
  }

  // 打开普通直播
  const onNormalLive = (item) => {
    // 跳转到直播播放页面
    uni.navigateTo({
      url: `/pages/livePlayer/index?id=${item.id}&title=${encodeURIComponent(item.title)}&time=${encodeURIComponent(item.time)}&category=${encodeURIComponent(item.category || '体育')}`
    })
  }

  // 打开视频号回放
  const onChannelsReplay = (item) => {
    if (item.isChannelsLive && item.channelsInfo) {
      console.log('准备打开视频号回放:', item.channelsInfo)

      // 检查微信版本是否支持
      const systemInfo = uni.getSystemInfoSync()
      const version = systemInfo.version

      if (compareVersion(version, '8.0.0') < 0) {
        uni.showModal({
          title: '版本过低',
          content: '当前微信版本过低，无法打开视频号回放，请升级微信版本',
          showCancel: false
        })
        return
      }

      // 显示加载提示
      uni.showLoading({ title: '正在打开回放...' })

      // 打开微信原生视频号回放播放器
      wx.openChannelsLive({
        finderUserName: item.channelsInfo.finderUserName,
        success: (res) => {
          console.log('成功打开视频号回放:', res)
          uni.hideLoading()
          uni.showToast({
            title: '回放已打开',
            icon: 'success'
          })
        },
        fail: (err) => {
          console.error('打开视频号回放失败:', err)
          uni.hideLoading()

          // 根据错误类型给出不同提示
          let errorMsg = '打开回放失败，请稍后重试'
          if (err.errMsg) {
            if (err.errMsg.includes('cancel')) {
              errorMsg = '用户取消打开回放'
            } else if (err.errMsg.includes('fail')) {
              errorMsg = '回放可能已删除或无法访问'
            }
          }

          uni.showModal({
            title: '提示',
            content: errorMsg,
            showCancel: false
          })
        }
      })
    }
  }

  // 打开视频号直播
  const onChannelsLive = (item) => {
    if (item.isChannelsLive && item.channelsInfo) {
      console.log('准备打开视频号直播:', item.channelsInfo)

      // 检查微信版本是否支持
      const systemInfo = uni.getSystemInfoSync()
      const version = systemInfo.version

      if (compareVersion(version, '8.0.0') < 0) {
        uni.showModal({
          title: '版本过低',
          content: '当前微信版本过低，无法打开视频号直播，请升级微信版本',
          showCancel: false
        })
        return
      }

      // 显示加载提示
      uni.showLoading({ title: '正在打开直播...' })

      // 打开微信原生视频号直播播放器
      wx.openChannelsLive({
        finderUserName: item.channelsInfo.finderUserName,
        success: (res) => {
          console.log('成功打开视频号直播:', res)
          uni.hideLoading()
          uni.showToast({
            title: '直播已打开',
            icon: 'success'
          })
        },
        fail: (err) => {
          console.error('打开视频号直播失败:', err)
          uni.hideLoading()

          // 根据错误类型给出不同提示
          let errorMsg = '打开直播失败，请稍后重试'
          if (err.errMsg) {
            if (err.errMsg.includes('cancel')) {
              errorMsg = '用户取消打开直播'
            } else if (err.errMsg.includes('fail')) {
              errorMsg = '直播可能已结束或无法访问'
            }
          }

          uni.showModal({
            title: '提示',
            content: errorMsg,
            showCancel: false
          })
        }
      })
    }
  }

  // 版本比较函数
  const compareVersion = (v1, v2) => {
    const v1Parts = v1.split('.').map(Number)
    const v2Parts = v2.split('.').map(Number)

    for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
      const v1Part = v1Parts[i] || 0
      const v2Part = v2Parts[i] || 0

      if (v1Part > v2Part) return 1
      if (v1Part < v2Part) return -1
    }

    return 0
  }

  // 格式化时间
  const formatTime = (timestamp) => {
    if (!timestamp) return ''
    const date = new Date(timestamp * 1000)
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  // 格式化观看人数
  const formatViewerCount = (count) => {
    if (count >= 10000) {
      return (count / 10000).toFixed(1) + '万'
    }
    return count.toString()
  }

  // 更新直播列表，添加视频号直播信息
  const updateLiveListWithChannelsInfo = (channelsData) => {
    // 清除之前的视频号直播项
    list.value = list.value.filter((item) => !item.isChannelsLive)

    // 添加新的视频号直播项
    channelsData.forEach((channel) => {
      if (channel.liveStatus === 1) {
        // 正在直播
        const liveItem = {
          id: `channels_${channel.finderUserName}`,
          img: channel.liveCover || imgUrl + 'a.jpg',
          title: `${channel.liveTitle || channel.nickname} 直播中`,
          time: '正在直播',
          isLive: true,
          isChannelsLive: true,
          updateTime: channel.updateTime || Date.now(),
          channelsInfo: {
            finderUserName: channel.finderUserName,
            nickname: channel.nickname,
            signature: channel.description || '',
            liveStatus: channel.liveStatus,
            liveTitle: channel.liveTitle || '',
            liveCover: channel.liveCover || ''
          }
        }

        // 添加到列表顶部
        list.value.unshift(liveItem)
      }
    })
  }

  // 获取视频号直播信息（带重试机制）
  const getChannelsInfo = async (retryCount = 3) => {
    for (let i = 0; i < retryCount; i++) {
      try {
        // 尝试调用PHP后端接口
        const res = await uni.request({
          url: 'https://your-domain.com/api/channels/live_status.php',
          method: 'POST',
          data: { channels: channelsConfig.value },
          timeout: 10000
        })

        if (res.data.code === 1) {
          return res.data.data
        }
      } catch (error) {
        console.error(`第${i + 1}次请求失败:`, error)

        if (i === retryCount - 1) {
          throw error
        }

        // 等待后重试
        await new Promise((resolve) => setTimeout(resolve, 1000 * (i + 1)))
      }
    }

    // 如果所有重试都失败，使用模拟数据
    return useMockData()
  }

  // 使用模拟数据
  const useMockData = () => {
    return channelsConfig.value.map((channel) => ({
      finderUserName: channel.finderUserName,
      nickname: channel.nickname,
      description: channel.description,
      liveStatus: Math.random() > 0.5 ? 1 : 0, // 随机模拟直播状态
      headimg: imgUrl + 'a.jpg',
      updateTime: Date.now()
    }))
  }

  // 定时检查直播状态
  const startStatusCheck = () => {
    if (statusCheckTimer) {
      clearInterval(statusCheckTimer)
    }

    // 每2分钟检查一次
    statusCheckTimer = setInterval(async () => {
      try {
        console.log('开始检查视频号直播状态...')
        const channelsData = await getChannelsInfo()
        updateLiveListWithChannelsInfo(channelsData)
        console.log('视频号状态更新完成')
      } catch (error) {
        console.error('定时检查直播状态失败:', error)
        uni.showToast({
          title: '直播状态更新失败',
          icon: 'none',
          duration: 2000
        })
      }
    }, 120000)
  }

  // 停止状态检查
  const stopStatusCheck = () => {
    if (statusCheckTimer) {
      clearInterval(statusCheckTimer)
      statusCheckTimer = null
    }
  }

  // 获取直播列表
  const getLiveList = async (page = 1, isLoadMore = false) => {
    if (isLoadMore) {
      isLoadingMore.value = true
    } else {
      isLoading.value = true
    }

    const params = {
      page: page,
      page_size: 10
    }

    try {
      const res = await API_EVENT_LIVE_POST(params)

      if (res.code === 1) {
        if (res.data && res.data.length > 0) {
          // 处理直播数据，添加标识
          const newData = res.data.map((item) => ({
            ...item,
            id: item.id || `normal_${Date.now()}_${Math.random()}`,
            isChannelsLive: false,
            isLive: item.status === 1,
            category: item.category || '体育',
            viewerCount: item.viewerCount || 0,
            homeTeam: item.homeTeam || '主队',
            awayTeam: item.awayTeam || '客队',
            venue: item.venue || '比赛场地'
          }))

          if (isLoadMore) {
            list.value.push(...newData)
          } else {
            list.value = newData
          }

          hasMore.value = newData.length === 10
        } else {
          if (isLoadMore) {
            hasMore.value = false
          } else {
            // 如果没有数据，使用模拟数据
            list.value = getMockLiveData()
          }
        }
      } else {
        // 如果API失败，使用模拟数据
        if (!isLoadMore) {
          list.value = getMockLiveData()
        }
        uni.showToast({ title: res.msg || '获取直播列表失败', icon: 'none' })
      }
    } catch (error) {
      console.error('获取直播列表失败:', error)
      // 如果网络错误，使用模拟数据
      if (!isLoadMore) {
        list.value = getMockLiveData()
      }
      uni.showToast({ title: '网络错误，请重试', icon: 'none' })
    } finally {
      if (isLoadMore) {
        isLoadingMore.value = false
      } else {
        isLoading.value = false
      }
    }
  }

  // 获取模拟直播数据
  const getMockLiveData = () => {
    return [
      {
        id: 'mock_1',
        title: '草源体育公开赛·郑州站',
        time: '09.12 13:00:00',
        img: imgUrl + 'stadium-1.jpg',
        isLive: false,
        isChannelsLive: false,
        category: '田径',
        homeTeam: '郑州队',
        awayTeam: '洛阳队',
        venue: '郑州体育中心',
        viewerCount: 1250
      },
      {
        id: 'mock_2',
        title: '全国青少年足球联赛',
        time: '09.12 15:30:00',
        img: imgUrl + 'stadium-2.jpg',
        isLive: true,
        isChannelsLive: false,
        category: '足球',
        homeTeam: '北京青年队',
        awayTeam: '上海青年队',
        venue: '北京工人体育场',
        viewerCount: 3200
      },
      {
        id: 'mock_3',
        title: 'CBA常规赛 广东vs辽宁',
        time: '09.12 19:30:00',
        img: imgUrl + 'stadium-3.jpg',
        isLive: false,
        isChannelsLive: false,
        category: '篮球',
        homeTeam: '广东宏远',
        awayTeam: '辽宁本钢',
        venue: '东莞篮球中心',
        viewerCount: 8900
      },
      {
        id: 'mock_4',
        title: '网球公开赛 半决赛',
        time: '09.12 20:00:00',
        img: imgUrl + 'stadium-4.jpg',
        isLive: true,
        isChannelsLive: false,
        category: '网球',
        homeTeam: '德约科维奇',
        awayTeam: '纳达尔',
        venue: '中央球场',
        viewerCount: 5600
      },
      {
        id: 'mock_5',
        title: '游泳锦标赛 100米自由泳',
        time: '09.12 21:15:00',
        img: imgUrl + 'stadium-5.jpg',
        isLive: false,
        isChannelsLive: false,
        category: '游泳',
        homeTeam: '中国队',
        awayTeam: '美国队',
        venue: '国家游泳中心',
        viewerCount: 2100
      },
      {
        id: 'mock_6',
        title: '马拉松比赛 全程直播',
        time: '09.12 07:00:00',
        img: imgUrl + 'stadium-6.jpg',
        isLive: false,
        isChannelsLive: false,
        category: '马拉松',
        homeTeam: '专业组',
        awayTeam: '业余组',
        venue: '城市马拉松赛道',
        viewerCount: 4500
      }
    ]
  }

  // // 加载更多
  // const loadMore = () => {
  //   if (isLoadingMore.value || !hasMore.value) return

  //   const nextPage = Math.floor(list.value.length / 10) + 1
  //   getLiveList(nextPage, true)
  // }
  const getEventList = async () => {
    let params = {
      page: 1,
      page_size: 10,
      lng: uni.getStorageSync('longitude'),
      lat: uni.getStorageSync('latitude')
    }
    feedId.value = '';
    try {
      const res = await API_HOME_EVENT_POST(params)
      console.log('getEventList', res)

      if (res.code === 1) {
        if (res.data.data.length > 0) {
          feedId.value = res?.data?.feedid
          if (feedId.value) {
            getChannelsLiveInfo(feedId.value) // 传字符串
          }
        }
      } else {
        uni.showToast({ title: res.msg, icon: 'none' })
      }
    } catch (error) {
      uni.showToast({ title: error.message, icon: 'none' })
    }
  }
  const getChannelsLiveInfo = (finderUserName) => {
    if (!finderUserName || typeof finderUserName !== 'string') {
      uni.showToast({ title: 'finderUserName 无效', icon: 'none' }); return
    }
    if (!wx.canIUse('getChannelsLiveInfo')) {
      uni.showToast({ title: '微信版本过低', icon: 'none' }); return
    }
    wx.getChannelsLiveInfo({
      finderUserName,     // 必须是 sph 开头的视频号ID
      // 可选：startTime, endTime
      success(res) {
        console.log('getChannelsLiveInfo ok:', res)
      },
      fail(err) {
        console.error('getChannelsLiveInfo fail:', err)
      }
    })
  }
  // 页面显示时
  onShow(async () => {
    getEventList()
    // channelsConfig.value = [
    //   {
    //     finderUserName: '草源田径小将',
    //     nickname: '草源田径',
    //     description: '专注田径运动推广',
    //     category: '体育'
    //   },
    //   {
    //     finderUserName: '体育频道',
    //     nickname: '体育频道',
    //     description: '体育资讯和直播',
    //     category: '体育'
    //   }
    // ]

    // // 获取直播列表
    // await getLiveList()

    // try {
    //   // 获取视频号直播信息
    //   const result = await getChannelsInfo()
    //   console.log('获取到的视频号信息:', result)

    //   if (result && result.length > 0) {
    //     updateLiveListWithChannelsInfo(result)
    //   }

    //   // 启动定时检查直播状态
    //   startStatusCheck()
    // } catch (error) {
    //   console.error('获取视频号信息失败:', error)
    //   uni.showToast({
    //     title: '获取直播信息失败',
    //     icon: 'none'
    //   })
    // }
  })

  // 页面隐藏时
  onHide(() => {
    stopStatusCheck()
  })
</script>

<style lang="scss" scoped>
  @import './index.scss';
</style>